import {loginIgnore} from '@/router/index'
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import {loadRoutes} from '@/utils/routerUtil'
import notification from 'ant-design-vue/es/notification'

/**
 * 检查认证信息
 * @param authType
 * @returns {boolean}
 */
function checkAuthorization() {
  const token = Vue.ls.get(ACCESS_TOKEN)
  if (token) {
    return true
  }
  return false
}
/**
 * 登录守卫
 * @param to
 * @param form
 * @param next
 * @param options
 */
const loginRoutePath = '/user/login'
const defaultRoutePath = '/system/userorg/userManager'
const loginGuard = (to, from, next, options) => {
  const {router,store,i18n} =options
  if (checkAuthorization()) {
    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath })
    }else{
      if(!store.state.user.userInfo){
        store.dispatch('GetInfo')
        .then(()=>{
          if(!store.state.user.addRouters||store.state.user.addRouters.length==0){
            store.dispatch('GetRouterMenu')
            .then((result)=>{
              if(result&&result.length>0){
                loadRoutes({router,store,i18n},store.state.user.addRouters)
                const redirect = decodeURIComponent(from.query.redirect || to.path)
                if (to.path === redirect) {
                  // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                  next({ ...to, replace: true })
                } else {
                  // 跳转到目的路由
                  next({ path: redirect })
                }
              }else{
                notification.warn({
                  message: '警告',
                  description: '未分配功能权限，请联系管理员'
                })
                // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
                store.dispatch('Logout').then(() => {
                  next({ path: loginRoutePath })
                })
              }
              
            }).catch(()=>{
              // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
              store.dispatch('Logout').then(() => {
                next({ path: loginRoutePath })
              })
            })
          }
        }).catch(()=>{
          notification.error({
            message: '错误',
            description: '请求用户信息失败，请重试'
          })
          // 失败时，获取用户信息失败时，调用登出，来清空历史保留信息
          store.dispatch('Logout').then(() => {
            next({ path: loginRoutePath, query: { redirect: to.fullPath } })
          })
        })
      }else{
        next()
      }
    }
  }else{
    if(loginIgnore.includes(to)){
      next()
    }else{
     
      next({path: loginRoutePath})
    }
  } 
}


/**
 * 混合导航模式下一级菜单跳转重定向
 * @param to
 * @param from
 * @param next
 * @param options
 * @returns {*}
 */
const redirectGuard = (to, from, next, options) => {
  const {store} = options
  const getFirstChild = (routes) => {
    const route = routes[0]
    if (!route.children || route.children.length === 0) {
      return route
    }
    return getFirstChild(route.children)
  }
  if (store.state.setting.layout === 'mix') {
    const firstMenu = store.getters['setting/firstMenu']
    if (firstMenu.find(item => item.fullPath === to.fullPath)) {
      store.commit('setting/setActivatedFirst', to.fullPath)
      const subMenu = store.getters['setting/subMenu']
      if (subMenu.length > 0) {
        const redirect = getFirstChild(subMenu)
        return next({path: redirect.fullPath})
      }
    }
  }
  next()
}
const routerAfter = ((to, from, options) => {
  const {store} =options
  store.dispatch('setCurrentRouter', to)
})
export default {
  beforeEach: [loginGuard, redirectGuard],
  afterEach: [routerAfter]
}
